import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { UserList as Entity } from '@/entity/user/user_list.entity';

@Injectable()
export class UserDao {

    public connection = getConnection();
    constructor(@InjectRepository(Entity)
    private readonly repository: Repository<Entity>,
    ) { }

    /**
     * 查询所有
     */
    findAll(param: any): Promise<Entity[]> {
        let sql = "select A.*,B.role_id,C.role_name,D.business_name from user_list as A "
            + "left outer join user_role_relation as B on (A.id = B.user_id) "
            + "left outer join user_role as C on (C.id = B.role_id) "
            + "left outer join business as D on (D.id = A.business_id) "
            + "order by id desc";
        return this.connection.query(sql);
    }

    /**
     * 按条件查询
      */
    findWhere(params: any): Promise<Entity> {
        return this.repository.findOne(params);
    }

    /**
     * 添加
     */
    add(params: any): Promise<Entity> {
        let entity = new Entity();
        Object.assign(entity, params);
        return this.repository.save(entity);
    }

    /**
     * 修改
     * @param params 
     */
    async update(params: any): Promise<Entity> {
        let entity = await this.repository.findOne(params.id);
        Object.assign(entity, params);
        return this.repository.save(entity);
    }

    /**
     * 删除
     * @param params 
     */
    async delete(params: any): Promise<Entity> {
        let entity = await this.repository.findOne(params.id);
        return this.repository.remove(entity);
    }
}
